package com.hulman.oms.service;

import com.hulman.oms.bean.Accessory;
import com.hulman.oms.bean.Device;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.IotDevice;
import com.hulman.oms.dao.DeviceDao;
import com.hulman.oms.dao.IotDeviceDao;
import com.hulman.oms.exception.IoTException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class IotDeviceService
{
    @Autowired
    private IotDeviceDao iotDeviceDao;
    @Autowired
    private DeviceDao deviceDao;

    public List<IotDevice> findIotDevices(Map<String, Object> map)
    {
        return iotDeviceDao.findIotDevices(map);
    }

    public Integer findIotDevicesCount(Map<String, Object> map)
    {
        return iotDeviceDao.findIotDevicesCount(map);
    }

    public Result findIotDevicesResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = iotDeviceDao.findIotDevicesCount(map);
        List<IotDevice> data = iotDeviceDao.findIotDevices(map);
        return new Result(data, count);
    }

    public IotDevice findIotDeviceById(Integer id)
    {
        return iotDeviceDao.findIotDeviceById(id);
    }

    public IotDevice findIotDeviceByIotCode(String iotCode)
    {
        return iotDeviceDao.findIotDeviceByIotCode(iotCode);
    }

    public void saveIotDevice(IotDevice iotDevice)
    {
        if (iotDevice.getId() != null && iotDevice.getId() != 0)
        {
            iotDeviceDao.updateIotDevice(iotDevice);
        } else
        {
            iotDeviceDao.insertIotDevice(iotDevice);
        }
    }

    public void deleteIotDeviceById(Integer id)
    {
        iotDeviceDao.deleteIotDeviceById(id);
    }

    public void deleteIotDevices(int[] ids)
    {
        iotDeviceDao.deleteIotDevices(ids);
    }

    public void clearIotDevicesByDeviceId(Integer deviceId)
    {
        iotDeviceDao.clearIotDevicesByDeviceId(deviceId);
    }

    public void importIotDevice(IotDevice iotDevice)
    {
        Device device = deviceDao.findDeviceByCode(iotDevice.getDeviceCode());
        if (device == null)
        {
            throw new IoTException("导入物联设备失败，找不到设备编号：" + iotDevice.getDeviceCode());
        }
        IotDevice iotDev = iotDeviceDao.findIotDeviceByDeviceIdAndIotName(device.getId(), iotDevice.getIotName());
        if (iotDev != null)
        {
            iotDevice.setId(iotDevice.getId());
        }
        iotDevice.setDeviceId(device.getId());
        saveIotDevice(iotDevice);
    }
}
